package com.atguigu.juc.volatiles;

import java.util.concurrent.TimeUnit;

/**
 * @author yanglin
 * @create 2024-01-23 14:35 星期二
 * description:
 */
public class VolatileNoAtomicDemo {

    public static void main(String[] args) {
        /**
         * volatile不保证原子性
         *  volatile变量不适合参与到依赖当前值的运算，通常适用于保存某个状态的boolean值或int值
         */
        MyNumber myNumber = new MyNumber();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    myNumber.addPlusPlus();
                }
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(myNumber.number);
    }
    
}

class MyNumber{
    volatile int number;
    public void addPlusPlus(){
        number++;
    }
}
